import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterapp/chapter/seven/dialog_checkbox_widget.dart';
import 'package:flutterapp/chapter/seven/show_custom_dialog.dart';

/// @date 2020/08/05  11:07
/// @author 程志强
/// @des 对话框详解

class DialogRoute1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("对话框详解"),
      ),
      body: Container(
        margin: EdgeInsets.symmetric(horizontal: 20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: _list(context),
        ),
      ),
    );
  }

  List<Widget> _list(BuildContext context) => [
        RaisedButton(
            child: Text("对话框1_AlertDialog"),
            onPressed: () async {
              bool delete = await showDeleteConfirmDialog1(context);
              if (delete == null) {
                print("取消删除==dialog1");
              } else {
                print("确定删除==dialog1");
                print("===删除文件。。。。==");
              }
            }),
        RaisedButton(
            child: Text("对话框2_SimpleDialog"),
            onPressed: () => changeLanguage(context)),
        RaisedButton(
            child: Text("对话框2_listDialog"),
            onPressed: () => showListDialog(context)),
        RaisedButton(
            child: Text("自定义对话框"),
            onPressed: () async {
              bool delete = await showMyCustomDialog(context);
              if (delete == null) {
                print("取消删除==custom dialog");
              } else {
                print("确定删除==custom dialog");
                print("===删除文件。。。。==");
              }
            }),
        RaisedButton(
            child: Text("内部复选框对话框_StatefulWidget"),
            onPressed: () async {
              bool delete = await showCheckboxDialog(context);
              if (delete == null) {
                print("取消删除==");
              } else {
                print("确定删除,同时删除子目录：$delete===");
              }
            }),
        RaisedButton(
            child: Text("内部复选框对话框_StatefulBuilder"),
            onPressed: () async {
              bool delete = await showCheckboxDialog2(context);
              if (delete == null) {
                print("取消删除==");
              } else {
                print("确定删除,同时删除子目录：$delete===");
              }
            }),
        RaisedButton(
            child: Text("内部复选框对话框_element.markNeedsBuild()"),
            onPressed: () async {
              bool delete = await showCheckboxDialog3(context);
              if (delete == null) {
                print("取消删除==");
              } else {
                print("确定删除,同时删除子目录：$delete===");
              }
            }),
        RaisedButton(
            child: Text("内部复选框对话框_element.markNeedsBuild只刷新checkbox"),
            onPressed: () async {
              bool delete = await showCheckboxDialog4(context);
              if (delete == null) {
                print("取消删除==");
              } else {
                print("确定删除,同时删除子目录：$delete===");
              }
            }),
        RaisedButton(
            child: Text("底部菜单列表"),
            onPressed: () async {
              int index = await showModalBottomSheetList(context);
              print("点击了item：$index===");
            }),
        RaisedButton(
            child: Text("Loading框"),
            onPressed: () {
              showLoadingDialog(context);
            }),
        RaisedButton(
            child: Text("Loading小框"),
            onPressed: () {
              showLoadingDialog2(context);
            }),
        RaisedButton(
            child: Text("日期选择showDatePicker"),
            onPressed: () async {
              DateTime dateTime = await showSelectDate(context);
              print("===选择了日期：$dateTime===");
            }),
        RaisedButton(
            child: Text("日期选择showCupertinoModalPopup"),
            onPressed: () async {
              DateTime dateTime = await showSelectIOSDate(context);
              print("===选择了日期IOS：$dateTime===");
            }),
      ];

  /// 删除文件对话框
  Future<bool> showDeleteConfirmDialog1(BuildContext context) {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("您确定要删除当前文件吗？"),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () => Navigator.of(context).pop(), //关闭对话框
              ),
              FlatButton(
                  child: Text("删除"),
                  onPressed: () => Navigator.of(context).pop(true))
            ],
          );
        });
  }

  /// SimpleDialog
  Future<void> changeLanguage(BuildContext context) async {
    int i = await showDialog<int>(
        context: context,
        builder: (BuildContext context) {
          return SimpleDialog(
            title: const Text("选择语言"),
            children: <Widget>[
              SimpleDialogOption(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 6),
                    child: Text("中文简体"),
                  ),
                  onPressed: () => Navigator.pop(context, 1) //返回1 ,
                  ),
              SimpleDialogOption(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 6),
                    child: Text("美国英语"),
                  ),
                  onPressed: () => Navigator.pop(context, 2) //返回2 ,
                  )
            ],
          );
        });

    if (i != null) {
      print("选择了：${i == 1 ? "中文简体" : "美国英语"}");
    }
  }

  /// 列表dialog
  Future<void> showListDialog(BuildContext context) async {
    int index = await showDialog<int>(
        context: context,
        builder: (context) {
          var child = Column(
            children: <Widget>[
              ListTile(
                title: Text("请选择"),
              ),
              Expanded(
                child: ListView.builder(
                    itemCount: 30,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text("$index"),
                        onTap: () => Navigator.of(context).pop(index),
                      );
                    }),
              )
            ],
          );
          /*        return Dialog(
            child: Container(
              height: 300,
              child: child,
            ),
          );  */

          return UnconstrainedBox(
            constrainedAxis: Axis.vertical,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxWidth: 280),
              child: Material(
                child: child,
                type: MaterialType.card,
              ),
            ),
          );
        });

    if (null != index) {
      print("点击了：$index");
    }
  }

  ///自定义对话框
  Future<bool> showMyCustomDialog(BuildContext context) {
    return showCustomDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("您确定要删除当前文件吗？"),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () => Navigator.of(context).pop(), //关闭对话框
              ),
              FlatButton(
                  child: Text("删除"),
                  onPressed: () => Navigator.of(context).pop(true))
            ],
          );
        });
  }

  /// 内部复选框对话框
  Future<bool> showCheckboxDialog(BuildContext context) {
    // 记录复选框是否选中
    bool _withTree = false;
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text("您确定要删除当前文件吗？"),
                Row(
                  children: <Widget>[
                    Text("同时删除子目录？"),
                    DialogCheckbox(
                      value: _withTree, // 默认不选中
                      onChanged: (bool v) {
                        // 更新选中状态
                        _withTree = !_withTree;
                      },
                    ),
                  ],
                )
              ],
            ),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () => Navigator.of(context).pop(),
              ),
              FlatButton(
                child: Text("删除"),
                onPressed: () {
                  // 将选中状态返回
                  Navigator.of(context).pop(_withTree);
                },
              ),
            ],
          );
        });
  }

  /// 内部复选框对话框 builder
  Future<bool> showCheckboxDialog2(BuildContext context) {
    // 记录复选框是否选中
    bool _withTree = false;
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text("您确定要删除当前文件吗？"),
                Row(
                  children: <Widget>[
                    Text("同时删除子目录？"),
                    //使用StatefulBuilder来构建StatefulWidget上下文
                    StatefulBuilder(
                      builder: (context, _setSate) {
                        return Checkbox(
                            value: _withTree,
                            onChanged: (bool v) {
                              //_setState方法实际就是该StatefulWidget的setState方法，
                              _setSate(() {
                                _withTree = !_withTree;
                              });
                            });
                      },
                    ),
                  ],
                )
              ],
            ),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () => Navigator.of(context).pop(),
              ),
              FlatButton(
                child: Text("删除"),
                onPressed: () {
                  // 将选中状态返回
                  Navigator.of(context).pop(_withTree);
                },
              ),
            ],
          );
        });
  }

  /// 内部复选框对话框 element.markNeedsBuild()
  Future<bool> showCheckboxDialog3(BuildContext context) {
    // 记录复选框是否选中
    bool _withTree = false;
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text("您确定要删除当前文件吗？"),
                Row(
                  children: <Widget>[
                    Text("同时删除子目录？"),
                    Checkbox(
                        value: _withTree,
                        onChanged: (bool v) {
                          // 此时context为对话框UI的根Element，我们
                          // 直接将对话框UI对应的Element标记为dirty
                          (context as Element).markNeedsBuild();
                          _withTree = !_withTree;
                        }),
                  ],
                )
              ],
            ),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () => Navigator.of(context).pop(),
              ),
              FlatButton(
                child: Text("删除"),
                onPressed: () {
                  // 将选中状态返回
                  Navigator.of(context).pop(_withTree);
                },
              ),
            ],
          );
        });
  }

  /// 内部复选框对话框 element.markNeedsBuild(),只刷新checkbox
  Future<bool> showCheckboxDialog4(BuildContext context) {
    // 记录复选框是否选中
    bool _withTree = false;
    return showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text("您确定要删除当前文件吗？"),
                Row(
                  children: <Widget>[
                    Text("同时删除子目录？"),
                    // 通过Builder来获得构建Checkbox的`context`，
                    // 这是一种常用的缩小`context`范围的方式
                    Builder(
                      builder: (context) {
                        return Checkbox(
                            value: _withTree,
                            onChanged: (bool v) {
                              // 此时context为对话框UI的根Element，我们
                              // 直接将对话框UI对应的Element标记为dirty
                              (context as Element).markNeedsBuild();
                              _withTree = !_withTree;
                            });
                      },
                    ),
                  ],
                )
              ],
            ),
            actions: <Widget>[
              FlatButton(
                child: Text("取消"),
                onPressed: () => Navigator.of(context).pop(),
              ),
              FlatButton(
                child: Text("删除"),
                onPressed: () {
                  // 将选中状态返回
                  Navigator.of(context).pop(_withTree);
                },
              ),
            ],
          );
        });
  }

  /// 底部菜单对话框
  Future<int> showModalBottomSheetList(BuildContext context) {
    return showModalBottomSheet(
        context: context,
        builder: (context) {
          return ListView.separated(
              itemCount: 30,
              separatorBuilder: (context, index) {
                return Divider();
              },
              itemBuilder: (context, index) {
                return ListTile(
                  title: Text("$index"),
                  onTap: () => Navigator.of(context).pop(index),
                );
              });
        });
  }

  /// loading框
  showLoadingDialog(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return AlertDialog(
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                CircularProgressIndicator(),
                Padding(
                  padding: const EdgeInsets.only(top: 26.0),
                  child: Text("正在加载，请稍后..."),
                ),
              ],
            ),
          );
        });
  }

  /// loading框2,修改dialog宽度
  showLoadingDialog2(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return UnconstrainedBox(
            constrainedAxis: Axis.vertical,
            child: SizedBox(
              width: 280,
              child: AlertDialog(
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    CircularProgressIndicator(),
                    Padding(
                      padding: const EdgeInsets.only(top: 26.0),
                      child: Text("正在加载，请稍后..."),
                    ),
                  ],
                ),
              ),
            ),
          );
        });
  }

  /// 日期选择
  Future<DateTime> showSelectDate(BuildContext context) {
    var date = DateTime.now();
    return showDatePicker(
        context: context,
        initialDate: date,
        firstDate: date,
        lastDate: date.add(Duration(days: 30)) // 未来30天可选
        );
  }

  /// ios分隔日期
  Future<DateTime> showSelectIOSDate(BuildContext context) {
    var date = DateTime.now();
    return showCupertinoModalPopup(
        context: context,
        builder: (context) {
          return SizedBox(
            height: 200,
            child: CupertinoDatePicker(
              mode: CupertinoDatePickerMode.dateAndTime,
              minimumDate: date,
              maximumDate: date.add(Duration(days: 30)),
              maximumYear: date.year + 1,
              onDateTimeChanged: (val) => print("====$val"),
            ),
          );
        });
  }
}
